<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-04-18
 * Time: 16:12
 */

namespace app\common\model;

use app\common\exception\ParameterException;
use app\common\exception\UploadException;
use app\common\service\Upload as UploadService;
use app\common\model\Atlas as AtlasModel;
use app\common\validate\UploadFile;

class Upload
{
    /**
     * 上传图集的图片到本地
     * @param $file
     * @param $category_id
     * @return array
     */
    public static function uploadImgListImage($file, $category_id)
    {
        $validate = new UploadFile();
        if (!$validate->scene('image_list')->check(['file'=>$file, 'category_id' => $category_id])) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        // 检查文件是否存在
        $file = self::checkFileIsExtra($file, $category_id);

        $file_info = UploadService::saveFile($file, UploadService::SAVE_TO_IMG_LIST);

        $result = AtlasModel::addImage($file_info, $category_id);

        if ($result) {
            return $result;
        } else {
            // 删除已上传的文件
            self::delUploadTempFile($file_info);
            return [];
        }

    }

    /**
     * 上传文件到本地
     * @param $file
     * @param $dir_name 保存文件夹的名称
     * @param string $type 保存文件的类型
     * @return array|void
     */
    public static function uploadFile($file, $dir_name, $type = 'file')
    {
        $validate = new UploadFile();
        $validate_result = false;
        // 判断上传的文件是什么类型
        switch ($type) {
            case UploadService::TYPE_IMAGE :
                $validate_result = $validate->scene('image')->check([
                    'file' => $file,
                    'type' => $type,
                    'dir_name' => $dir_name
                ]);
                break;
            default :
                $validate_result = $validate->scene('file')->check([
                    'file' => $file,
                    'type' => $type,
                    'dir_name' => $dir_name
                ]);
                break;
        }
        if (!$validate_result) {
            throw new UploadException([
                'msg' => $validate->getError()
            ]);
        }

        $file_info = UploadService::saveFile($file,UploadService::SAVE_TO_DIR,$dir_name);

        if ($type === UploadService::TYPE_IMAGE) {
            $file_info = self::addImageUrl($file_info);
        }

        return $file_info;
    }

    /**
     * 删除指定名字的文件
     * @param $file_name
     * @return bool
     */
    public static function deleteUploadTempFileFile($file_name)
    {
        delFile($file_name);

        return true;
    }


    /**
     * 判断上传的文件是否已经存在
     * @param $file
     * @param $category_id
     * @return array 返回可以进行添加的文件
     */
    private static function checkFileIsExtra($file, $category_id)
    {
        // 判断是否为数组
        if (is_array($file)) {

            for ($i = 0; $i < $file.length(); $i++) {
                // 获取md5和文件原名
                $origin_name = $file[$i]->getOriginalName();
                $md5 = $file[$i]->hash('md5');

                // 查找文件是否在数据库中存在
                if (AtlasModel::checkImageExtra($origin_name, $md5, $category_id)) {
                    // 删除数组中存在的元素（指定下标）
                    unset($file[$i]);
                    // 重组数组
                    $file = array_values($file);

                    $i--;
                }
            }

        } else {
            // 获取md5和文件原名
            $origin_name = $file->getOriginalName();
            $md5 = $file->hash('md5');

            // 查找文件是否在数据库中存在
            if (AtlasModel::checkImageExtra($origin_name, $md5, $category_id)) {
                throw new UploadException();
            }

        }

        return $file;
    }

    /**
     * 添加图片的url地址
     * @param $file_info
     * @return mixed
     */
    private static function addImageUrl($file_info)
    {
        // 判断是否为数组
        if (isset($file_info['save_path']) && is_array($file_info['save_path'])) {

            foreach ($file_info['save_path'] as $key => $value) {
                $file_info['img_url'][$key] = add_image_prefix($value);
            }

        } else {
            $file_info['img_url'] = add_image_prefix($file_info['save_path']);

        }

        return $file_info;
    }

    /**
     * 删除上传的临时文件
     * @param $file_info
     */
    private static function delUploadTempFile($file_info)
    {
        // 判断是否为数组
        if (isset($file_info['save_path']) && is_array($file_info['save_path'])) {

            foreach ($file_info['save_path'] as $key => $value) {
                delFile($value);
            }

        } else {
            delFile($file_info['save_path']);

        }
    }
}